package com.scud.order.listener;

import com.alibaba.fastjson.JSONObject;
import com.rabbitmq.client.Channel;
import com.scud.client.product.IProductClient;
import com.scud.common.constants.OrderStatus;
import com.scud.common.constants.RabbitmqConstants;
import com.scud.common.constants.RedisConstants;
import com.scud.model.order.dto.FullOrderDto;
import com.scud.model.order.pojo.Order;
import com.scud.order.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;


/**
 * @author vermouth
 */

@Component
@Slf4j
public class RabbitmqListener {
    @Autowired
    private OrderService orderService;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private IProductClient productClient;

    /**
     * 监听超时订单
     *
     * @param message:
     * @param channel:
     * @param tag:
     * @return void
     */
    @RabbitListener(queues = RabbitmqConstants.SCUD_ORDER_DEAD_QUEUE)
    public void orderDeadListener(String message, Channel channel, @Header(AmqpHeaders.DELIVERY_TAG) long tag) {
        //在此写订单超时相关逻辑（注意:无论订单是否确认最终都会进入私信队列，这里对订单状态没有更改的订单做处理）
        FullOrderDto orderDto = JSONObject.parseObject(message, FullOrderDto.class);
        //获取当前订单状态
        Order order = orderDto.getOrder();
        Map<Long, Integer> skuCount = orderDto.getSkuCount();
        Map<String, Integer> skus = new HashMap<>();
        order = orderService.getOrder(order.getId());
        if (order.getStatus() == OrderStatus.UNPAID.ordinal()) {
            //订单超时
            //1.更改订单状态
            orderService.updateOrderStatus(order.getId(), OrderStatus.TIME_OUT.ordinal());
            //2.恢复sku库存
            //2.1恢复redis数据
            Set<Map.Entry<Long, Integer>> entries = skuCount.entrySet();
            for (Map.Entry<Long, Integer> entry : entries) {
                stringRedisTemplate.opsForValue()
                        .increment(RedisConstants.SKU + entry.getKey(), entry.getValue());
                skus.put(entry.getKey() + "", entry.getValue());
            }
            //2.2远程调用product子系统恢复数据
            productClient.resetStock(skus);
        }

        try {
            //消息确认
            channel.basicAck(tag, false);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

}
